<template>
	<view style="padding-bottom: 40rpx;">
		<!-- #ifdef MP-WEIXIN -->
		<!-- 插屏广告 -->
		<adInter></adInter>

		<!-- 激励视频设置 -->
		<ad-rewarded-video ref="adRewardedVideo" adpid="1501138598" :preload="false" :disabled="true"
			v-slot:default="{adVideoLoading, adVideoError}" @load="onadload" @close="onadclose" @error="onaderror">
			<view class="ad-error" v-if="adVideoError">{{adVideoError}}</view>
		</ad-rewarded-video>
		<!-- #endif -->

		<u-transition :show="true" mode="fade-right">
			<view class="camera-btn">
				<u-button type="success" icon="camera-fill" iconColor="#fff" @click="distinguish('camera')"
					shape="circle" :customStyle="buttonCustomStyle" text="拍照识别(图片转文字)">
				</u-button>
			</view>
		</u-transition>

		<view class="tool">
			<u-transition :show="true" mode="fade-left">
				<view class="grid">
					<view class="item" hover-class="bg-light" @click="distinguish('album')">
						<view class="icon">
							<u-icon size="28" color="#fcbd71" name="photo-fill"></u-icon>
						</view>
						<view class="title">相册中选择</view>
					</view>
					<view class="item" hover-class="bg-light" @click="distinguish('msg')">
						<view class="icon">
							<u-icon size="28" color="#71d5a1" name="weixin-fill"></u-icon>
						</view>
						<view class="title">微信聊天记录中选择</view>
					</view>
				</view>
			</u-transition>
		</view>

		<!-- 图片裁剪框 -->
		<view>
			<ksp-cropper mode="free" :width="cropper.with" :height="cropper.height" :maxWidth="600" :maxHeight="600"
				:url="cropper.cropperUrl" @cancel="cropperCancel" @ok="cropperOk">
			</ksp-cropper>
		</view>

		<view style="display: flex;width: 90%;margin: 0 auto;">
			<view class="text-left" style="display: flex;align-items: center;flex: 1;">
				<view style="margin-right: 20rpx;color:rgba(0,0,0,.5);font-size: 30rpx;">保留格式</view>
				<u-switch v-model="switchVal" size="20" active-color="#1acc89" @change="setResFormat">
				</u-switch>
			</view>
			<view class="text-right">
				<u-button @click="showbig" size="small" color="#fef0f0" :customStyle="{color:'#f56c6c'}" text="查看原图">
				</u-button>
			</view>
		</view>

		<!-- 识别结果 -->
		<view class="img-content">
			<view class="result">
				<u-textarea class="text-light-black" maxlength="6000" height="280" count v-model="result"
					placeholder="在此处查看识别结果哦~~">
				</u-textarea>
			</view>
		</view>

		<view class="tool-bottom-box">
			<view class="tool-btn-item">
				<u-button size="medium" shape="circle" icon="cut" iconColor="#1acc89" @click="copy" color="#f0faf8"
					text="复制文本" :customStyle="{color:'#1acc89'}">
				</u-button>
			</view>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<!-- 信息流广告 -->
		<view class="ad-view">
			<adBanner></adBanner>
		</view>
		<!-- #endif -->
	</view>
</template>
<script>
	import adInter from '@/components/adInter/adInter.vue';
	import adBanner from '@/components/adBanner/adBanner.vue';
	import {
		pathToBase64,
		base64ToPath
	} from 'image-tools';
	export default {
		components: {
			adInter,
			adBanner
		},
		data() {
			return {
				imglist: [],
				original_img: '',
				result: '',
				adVideoLoading: false,
				adVideoError: '',
				userinfo: {},
				switchVal: true,
				dealData: '',
				formatData: '',
				buttonCustomStyle: {
					'background-color': '#1acc89'
				},
				cropper: {
					with: 300,
					height: 400,
					cropperUrl: '',
					imgPath: ''
				}
			};
		},
		onReady() {
			// #ifdef MP-WEIXIN
			this.$refs.adRewardedVideo.load()
			// #endif
		},
		onShareAppMessage(res) {
			return {
				title: '给你推荐一个超好用的图片转文字工具，解放双手！',
				path: '/pages/index/index',
			}
		},
		methods: {
			checkToken() {
				const token = uni.getStorageSync('token');
				if (token == '' || token == undefined) {
					return false
				} else {
					return true
				}
			},
			async getUserInfo() {
				return this.$http.requestApi('POST', 'client/getUserInfo', {
					loginType: 1,
					plat_type: this.$platType
				});
			},
			copy() {
				if (this.result == '') {
					uni.showToast({
						title: '复制内容不存在',
						icon: 'none'
					});
					return false;
				}
				uni.setClipboardData({
					data: this.result, //要被复制的内容
					success: () => { //复制成功的回调函数
						uni.showToast({ //提示
							title: "复制成功",
							icon: 'none'
						})
					}
				});
			},
			showbig() {
				if (this.original_img == '') {
					uni.showToast({
						icon: "none",
						title: "暂无识别记录"
					})
					return;
				}
				uni.previewImage({
					current: 0,
					urls: [this.original_img]
				})
			},
			setResFormat(e) {
				if (e) {
					//带格式
					this.result = this.formatData;
				} else {
					//不带格式
					this.result = this.dealData;
				}
			},
			//选择照片
			async distinguish(type) {
				let _this = this
				//检测用户是否登录
				let islogin = _this.checkToken();
				if (!islogin) {
					uni.navigateTo({
						url: '/pages/login/index'
					});
					return false;
				}
				//校检用户是否为vip
				let userinfo = await _this.getUserInfo();
				if (!userinfo.data.useable_num) {
					uni.showModal({
						title: '温馨提示',
						content: '您的免费使用次数不足，请观看视频或免费签到获得使用次数',
						cancelText: '立即签到',
						confirmText: '观看视频',
						success: function(res) {
							if (res.confirm) {
								//立即观看
								_this.adVideoLoading = true;
								_this.$refs.adRewardedVideo.show();
							} else if (res.cancel) {
								//立即签到
								uni.navigateTo({
									url: '/pages/user/signin'
								});
							}
						}
					});
					return false;
				}
				if (type == 'album' || type == 'camera') {
					let sourceType = [];
					if (type == 'album') {
						sourceType = ['album']
					}
					if (type == 'camera') {
						sourceType = ['camera']
					}
					uni.chooseImage({
						count: 1, //照片数量
						sizeType: ['compressed'], //压缩的图片
						sourceType, //拍照或者相机
						success(res) {
							uni.getImageInfo({
								src: res.tempFilePaths[0],
								success(imgInfo) {
									_this.cropper.with = imgInfo.width;
									_this.cropper.height = imgInfo.height;
									_this.original_img = res.tempFilePaths[0]; //选择图片返回的相对路径,
									_this.cropper.cropperUrl = res.tempFilePaths[0];
								}
							})
						}
					});
				} else {
					uni.chooseMessageFile({
						count: 1, //照片数量
						success(res) {
							uni.getImageInfo({
								src: res.tempFiles[0].path,
								success(imgInfo) {
									_this.cropper.with = imgInfo.width;
									_this.cropper.height = imgInfo.height;
									_this.original_img = res.tempFiles[0].path; //选择图片返回的相对路径,
									_this.cropper.cropperUrl = res.tempFiles[0].path;
								}
							})
						}
					})
				}
			},
			getImgInfo(img) {
				let _this = this;
				//将图片转为base64格式
				pathToBase64(img).then(base64Str => {
					_this.$http.requestApi('POST', 'ocr/img/toText', {
						img: base64Str,
						foo: 'accurateBasic',
						loginType: 1
					}).then(res => {
						if (res.status == 200) {
							_this.dealData = res.data.deal_data;
							_this.formatData = res.data.format_data
							if (_this.switchVal) {
								//带格式
								_this.result = res.data.format_data;
							} else {
								//不带格式
								_this.result = res.data.deal_data;
							}
						} else {
							//调用失败
							uni.showToast({
								icon: "none",
								title: res.msg,
							})
						}
					})
				}).catch(error => {
					uni.showToast({
						icon: "none",
						title: error
					})
				});
			},
			cropperOk(ev) {
				//关闭裁剪框
				this.cropper.cropperUrl = "";
				this.getImgInfo(ev.path);
			},
			cropperCancel() {
				// url设置为空，隐藏控件
				this.cropper.cropperUrl = "";
			},
			onadload(e) {
				this.adVideoLoading = false;
			},
			onadclose(e) {
				let that = this;
				const detail = e.detail
				// 用户点击了【关闭广告】按钮
				if (detail && detail.isEnded) {
					// 正常播放结束
					that.$http.requestApi('POST', 'client/reward/setUseableNum', {
						loginType: 1,
						plat_type: that.$platType
					}).then(res => {
						uni.showToast({
							icon: "none",
							title: res.msg
						});
					});
				} else {
					//播放中途退出
					uni.showToast({
						icon: "none",
						title: '中途退出，获取免费机会失败'
					})
				}
			},
			onaderror(e) {
				// 广告加载失败
				this.adVideoLoading = false;
				this.adVideoError = e;
			}
		}
	};
</script>

<style lang="scss">
	.camera-btn {
		width: 90%;
		margin: 30rpx auto 0 auto;
	}

	.result {
		.text-light-black {
			white-space: pre-wrap;
		}
	}

	.p-textarea {
		text-align: justify;
		height: calc(100vh - 600rpx);
		width: 100%;
		line-height: 180%;
		font-size: 28rpx;
		color: #555;
	}

	::-webkit-scrollbar {
		display: none;
	}

	.ad-view {
		padding: 20rpx;
	}

	.tool {
		width: 90%;
		margin: 15rpx auto;

		.header {
			.title {
				margin-bottom: 30rpx;
			}
		}

		.grid {
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			justify-content: space-between;

			.item {
				width: 48%;
				display: flex;
				flex-direction: column;
				align-items: center;
				background-color: #F0FAF8;
				margin: 15rpx 0rpx;
				padding: 30rpx 0rpx;
				border-radius: 10rpx;

				.title {
					color: #1B2B20;
					margin-top: 15rpx;
					font-size: 26rpx;
				}

				.desc {
					color: #67776C;
					font-size: 24rpx;
				}
			}
		}
	}

	.img-content {
		width: 90%;
		margin: 30rpx auto;
	}

	.tool-bottom-box {
		width: 90%;
		margin: 0 auto;
		display: flex;

		.tool-btn-item {
			text-align: center;
			width: 46%;
			flex: 1;

			&:nth-child(2) {
				margin-left: 4%;
			}
		}
	}
</style>